<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 110px;
  line-height: 178px;
  text-align: center;
}

.el-input__inner {
  border-radius: 92px;
  border-color: green;
}

.el-icon-arrow-right:before {
  margin-left: -11px;
}

.top-div {
  width: 400px;
  height: 114px;
  position: relative;
}

.el-input__icon {
  position: absolute;
  left: 3px;
  top: 1px;
}

.searchButton {
  position: absolute;
  left: 295px;
  top: 4px;
  border-radius: 10px;
  border-color: green;
  background-color: green;
}

.allListButton{
  position: absolute;
  left: 380px;
  top: 4px;
  border-radius: 10px;
  border-color: green;
  background-color: green;
}

.titleSpan {
  position: absolute;
  top: 14px;
  font-size: 17px;
}

.addButton {
  position: absolute;
  top: 60px;
  left: 90px;
  border-color: green;
}

.deleteButton {
  position: absolute;
  top: 60px;
  left: -1px;
}

.el-table--border th.el-table__cell, .el-table__fixed-right-patch {
  background-color: #333333;
  color: #ffffff;
}

.el-textarea__inner {
  border-color: #008000;
}

.el-dialog__title {
  font-family: 黑体;
  font-size: 25px;
}

.el-dialog__header {
  text-align: center;
}

.el-form-item__label {
  font-size: 18px;
  margin-top: 3px;
}

.formFoot {
  margin-left: -23px
}
</style>

<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }" style="font-size: 19px;">
        <i class="el-icon-s-home"></i> 个人中心
      </el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 17px">公告管理</el-breadcrumb-item>
    </el-breadcrumb>

    <div style="margin: 24px 0 12px 0">
      <el-divider></el-divider>
    </div>

    <div class="top-div">
      <span class="titleSpan">标题</span>
      <el-input style="width: 250px;position: absolute;left: 38px;top: 3px;"
                prefix-icon="el-icon-search" v-model="searchTitle" placeholder="请输入标题"></el-input>
      <el-button class="searchButton" type="primary" icon="el-icon-search" @click="showSearchPage1()">查询</el-button>
      <el-button class="allListButton" type="primary" icon="el-icon-search" @click="showAllNoticePage1()">展示全部</el-button>
      <el-button size="medium" round class="addButton" icon="el-icon-circle-plus"
                 @click="addNewFormVisible = true">新增
      </el-button>
      <el-popconfirm
          @confirm="deleteNotices()"
          confirm-button-text='确定'
          cancel-button-text='取消'
          icon="el-icon-info"
          icon-color="red"
          title="确定要删除选中的公告吗？">
        <el-button class="deleteButton" icon="el-icon-delete" round size="medium" type="danger"
                   slot="reference">删除
        </el-button>
      </el-popconfirm>
    </div>

    <!--  表格  -->
    <el-table
        empty-text="暂无数据，请再试一次！"
        class="table"
        ref="multipleTable"
        :data="noticeData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39"></el-table-column>
      <el-table-column prop="id" header-align="center" align="center" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" :show-overflow-tooltip="true" header-align="center" align="center" label="标题"
                       width="599"></el-table-column>
      <el-table-column prop="photo" header-align="center" align="center" label="图片" width="260">
        <template slot-scope="scope">
          <img
              style="width: 120px; height: 100px"
              :src="scope.row.photo<1||scope.row.photo==null?'':require('../img/admin/'+scope.row.photo)"
              :alt="scope.row.photo<1?'未发布':'加载失败'">
        </template>
      </el-table-column>
      <el-table-column prop="admName" header-align="center" align="center" label="发布人"
                       width="173"></el-table-column>
      <el-table-column prop="noticeCreate" header-align="center" align="center" label="发布日期"
                       width="173"></el-table-column>

      <!--操作-->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-document" round size="small"
                     @click="openStandardDialog(scope.row)">详情
          </el-button>
          <el-button type="success" icon="el-icon-edit" round size="small"
                     @click="openEditDialog(scope.row)">修改
          </el-button>
          <el-button type="danger" icon="el-icon-delete" round size="small"
                     @click="confirmDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px;">
      <el-button style="border-radius: 30px;" @click="toggleSelection()">取消选择</el-button>
    </div>

    <!--  弹出添加公告的弹框  -->
    <el-dialog :destroy-on-close="true" title="添加公告" :visible.sync="addNewFormVisible">
      <el-form :model="noticeForm" :rules="rules" ref="noticeForm" label-width="100px" class="demo-ruleForm">
        <el-form-item prop="title" label="标题" :label-width="formLabelWidth">
          <el-input type="textarea" autosize placeholder="请输入标题" maxlength="20" show-word-limit
                    minlength="2" v-model="noticeForm.title">
          </el-input>
        </el-form-item>
        <el-form-item prop="content" label="正文" :label-width="formLabelWidth">
          <el-input
              :rol="10"
              maxlength="1000"
              minlength="2"
              show-word-limit
              type="textarea"
              :rows="20"
              placeholder="请输入正文内容"
              v-model="noticeForm.content">
          </el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              :on-remove="handleRemove"
              :limit="1"
              list-type="picture-card"
              class="avatar-uploader"
              action="http://localhost:8081/admin/upload"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item class="formFoot">
          <el-button style="border-radius: 30px" @click="resetForm('noticeForm')">重置</el-button>
          <el-button style="border-radius: 30px" @click="addNewFormVisible = false">取消</el-button>
          <el-button style="background-color: #008000; border-radius: 30px" type="primary"
                     @click="submitAddNewForm('noticeForm')">添加
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--  修改公告弹框  -->
    <el-dialog style="border-radius: 30px" :title="updateDialogTitle" :visible.sync="editFormVisible">
      <el-form :model="updateForm" :rules="rules" ref="updateForm" label-width="100px" class="demo-ruleForm">
        <el-form-item prop="title" label="标题" :label-width="formLabelWidth">
          <el-input type="textarea" autosize placeholder="请输入标题" maxlength="20" show-word-limit
                    minlength="2" v-model="updateForm.title">
          </el-input>
        </el-form-item>
        <el-form-item prop="content" label="正文" :label-width="formLabelWidth">
          <el-input
              maxlength="1000"
              minlength="2"
              show-word-limit
              type="textarea"
              :rows="20"
              placeholder="请输入正文内容"
              v-model="updateForm.content">
          </el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8081/admin/upload"
              :show-file-list="false"
              :on-success="handleSuccess2"
              :before-upload="beforeAvatarUpload">
            <img v-if="this.updateForm.photo" :src="photoUrl!=''?photoUrl:require('../img/admin/'+updateForm.photo)" style="height: 110px;width: 150px;display: block"
                 class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item class="formFoot">
          <el-button style="border-radius: 30px" @click="resetForm('updateForm')">重置</el-button>
          <el-button style="border-radius: 30px" @click="editFormVisible = false">取消</el-button>
          <el-button style="background-color: #008000; border-radius: 30px" type="primary"
                     @click="submitUpdateForm('updateForm')">修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--    公告详情弹框    -->
    <el-dialog :visible.sync="StandardVisible" width="1000px">
      <div align="center" style="flex-wrap: nowrap;">
        <h1 style="margin:0 auto;font-size: 30px">{{ noticeStandard.title }}</h1>
        <span style="margin-right: 20px">发布人：{{ noticeStandard.admName }}</span>
        <span>{{ noticeStandard.noticeCreate }}</span>
        <pre align="left" style="white-space: pre-line; font-size: 20px;margin: 15px auto;">{{ noticeStandard.content }}</pre>
        <img v-show="noticeStandard.photo<1?false:true"
             :src="noticeStandard.photo<1||noticeStandard.photo==null?'':require('../img/admin/'+noticeStandard.photo)"
             alt="加载失败" style="width: 600px;height: 350px;">
        <br>
        <br>
        <span>最近更新时间：{{ noticeStandard.noticeModified }}</span>
      </div>
    </el-dialog>

    <!--  分页  -->
    <div class="block" align="center" style="margin-top: 10px;margin-bottom: 15px">
      <el-pagination
          v-show="titleListShow"
          background
          @current-change="handleCurrentChange"
          :current-page.sync="titleList.page"
          :page-size="titleList.pageSize"
          layout="prev, pager, next, jumper"
          :total="this.totalCount">
      </el-pagination>
      <el-pagination
          v-show="allListShow"
          background
          @current-change="handleCurrentChange1"
          :current-page.sync="allList.page"
          :page-size="allList.pageSize"
          layout="prev, pager, next, jumper"
          :total="this.totalCount">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      photoUrl:'',
      noticeStandard: {},
      totalCount: 0,
      titleListShow:false,
      allListShow:false,
      titleList: {
        pageSize: 4,
        page: 1,
      },
      allList: {
        pageSize: 4,
        page: 1,
      },
      searchTitle: '',
      addNewFormVisible: false,
      editFormVisible: false,
      StandardVisible: false,
      formLabelWidth: '75px',
      srcList: [],
      noticeData: [],
      ids: [],
      updateDialogTitle: '',
      noticeForm: {
        title: '公告标题测试001',
        content: '公告正文测试001',
        photo: ''
      },
      updateForm: {
        id: '',
        title: '',
        content: '',
        photo: ''
      },
      rules: {
        title: [
          {required: true, message: '请输入公告标题', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入公告正文', trigger: 'blur'},
          {min: 2, max: 1000, message: '长度在 2 到 1000 个字符', trigger: 'blur'}
        ],
      },
      multipleSelection: [],
      showCurrentList:0,
    }
  },
  methods: {
    //撤销上传图片
    handleRemove(file, fileList) {
      console.log("需要移除的文件是"+file, fileList);
      console.log("需要移除的uuid值是"+file.response);
      let url = 'http://localhost:8081/admin/uploadDelete/uuid=' + file.response;
      console.log('执行图片撤销的请求路径是：'+url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$notify.success({
            title: '提示',
            message: '撤销图片成功！',
            showClose: true,
            position: 'top-right'
          });
          this.noticeForm.photo = '';
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-right'
          });
        }
      });
    },

    //展示所有公告第一页
    showAllNoticePage1(){
      this.allList.page = 1;
      this.loadNoticeList();
    },
    //展示搜索公告第一页
    showSearchPage1(){
      this.titleList.page = 1;
      this.search();
    },

    //展示当前列表
    showCurrentNoticeList() {
      if (this.showCurrentList == 1) {
        this.showCurrentList = 0;
        this.loadNoticeList();
      } else if (this.showCurrentList == 2) {
        this.showCurrentList = 0;
        this.search();
      }
    },

    //图片上传成功后
    handleSuccess(response,file) {
      console.log(response);
      this.noticeForm.photo = response;
    },
    handleSuccess2(response,file) {
      console.log(response);
      this.updateForm.photo = response;
      this.photoUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    handleCurrentChange(val) {
      this.titleList.page = val;
      this.showCurrentNoticeList();
      console.log(`当前页: ${val}`);
    },
    handleCurrentChange1(val) {
      this.allList.page = val;
      this.showCurrentNoticeList();
      console.log(`当前页: ${val}`);
    },

    //取消选择方法
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //选择方法
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log('多选框数据是：' + JSON.stringify(this.multipleSelection));
    },

    //执行多项删除
    deleteNotices() {
      (this.ids).length = 0;
      if ((this.multipleSelection).length == 0) {
        this.$notify.warning({
          title: '提示',
          message: '请选择公告！',
          showClose: false,
          position: 'top-left'
        });
        return;
      }
      for (let data of this.multipleSelection) {
        this.ids.push(data.id);
      }
      console.log('ids是：' + JSON.stringify(this.ids))

      let url = 'http://localhost:8081/notice/deleteIds';
      console.log('批量删除公告请求的url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .post(url, this.ids).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$notify.success({
            title: '提示',
            message: '删除成功！',
            showClose: true,
            position: 'top-left'
          });
          this.showCurrentNoticeList();
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-left'
          });
          this.showCurrentNoticeList();
        }
      });
    },

    //展示公告列表
    loadNoticeList() {
      this.showCurrentList = 1;
      this.allListShow = true;
      this.titleListShow = false;
      let url = 'http://localhost:8081/notice/' + this.allList.page + '/' + this.allList.pageSize + '/admNoticeList';
      console.log('公告展示请求的url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.noticeData = responseBody.data.list;
          this.totalCount = responseBody.data.totalCount;
        } else {
          this.$notify.error({
            title: '提示',
            message: responseBody.message,
            showClose: false,
            position: 'top-left'
          });
        }
      })
    },

    //展示详情
    openStandardDialog(notice) {
      let url = 'http://localhost:8081/notice/' + notice.id + '/admNoticeStandard';
      console.log('公告详情请求的url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.StandardVisible = true;
          this.noticeStandard = responseBody.data;
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-left'
          });
          this.showCurrentNoticeList();
        }
      })
    },

    //模糊搜索标题
    search() {
      this.titleListShow = true;
      this.allListShow = false;
      let url = 'http://localhost:8081/notice/' + this.titleList.page + '/' + this.titleList.pageSize + '/title=' + this.searchTitle + '/AdmSearchNoticeList';
      console.log('查询标题展示列表请求的url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.showCurrentList = 2;
          this.noticeData = responseBody.data.list;
          this.totalCount = responseBody.data.totalCount;
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: false,
            position: 'top-left'
          });
        }
      })
    },

    //弹出确认删除框
    confirmDelete(notice) {
      console.log('尝试打开删除[id=' + notice.id + ']数据的对话框');
      let message = '此操作将永久删除【' + notice.title + '】公告, 是否继续?';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(notice);
      }).catch(() => {
      });
    },

    //执行删除
    handleDelete(notice) {
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .post('http://localhost:8081/notice/' + notice.id + '/delete').then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message.success('删除成功！');
          this.showCurrentNoticeList();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.showCurrentNoticeList();
            }
          });
        } else {
          this.$message.error(responseBody.message);
          this.showCurrentNoticeList();
        }
      });
    },

    //执行添加公告
    submitAddNewForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:8081/notice/addNew';
          console.log('URL = ' + url);
          let formData = this.qs.stringify(this.noticeForm);
          console.log('formData = ' + formData);

          let adminJwt = localStorage.getItem('adminJwt');
          this.axios.create({'headers': {'Authorization': adminJwt}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.$notify.success({
                title: '提示',
                message: "添加公告成功！",
                showClose: true,
                position: 'top-right'
              });
              this.addNewFormVisible = false;
              this.showCurrentNoticeList();
              this.noticeForm.photo = '';
            } else {
              this.$notify.error({
                title: '提示',
                message: responseBody.message,
                showClose: false,
                position: 'top-right'
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //弹出修改框
    openEditDialog(notice) {
      console.log('尝试打开编辑[id=' + notice.id + ']数据的对话框');

      let url = 'http://localhost:8081/notice/' + notice.id + '/admNoticeStandard';
      console.log('url = ' + url);

      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.updateDialogTitle = '修改【' + notice.title + '】公告';
          this.updateForm = responseBody.data;
          this.editFormVisible = true;
        } else {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.showCurrentNoticeList();
            }
          });
        }
      })
    },

    //提交修改
    submitUpdateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = this.qs.stringify(this.updateForm);
          console.log(formData);

          let url = 'http://localhost:8081/notice/' + this.updateForm.id + '/update';
          console.log('URL = ' + url);

          this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.photoUrl = '';
              this.$message.success("修改公告信息成功！");
              this.editFormVisible = false;
              this.showCurrentNoticeList();
            } else if (responseBody.state == 40400) {
              this.$alert(responseBody.message, '警告', {
                confirmButtonText: '确定',
                callback: action => {
                  this.editFormVisible = false;
                  this.showCurrentNoticeList();
                }
              });
            } else {
              this.$message.error(responseBody.message);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //清空添加输入框
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  mounted() {
    this.loadNoticeList();
  }
}
</script>

